package com.p2p.auth.controller.api.app;


import com.p2p.auth.common.base.JsonResult;
import com.p2p.auth.common.base.ResponseBase;
import com.p2p.auth.common.base.ResultCode;
import com.p2p.auth.controller.Routes;
import com.p2p.auth.domain.entity.User;
import com.p2p.auth.service.lifeCycle.UserUtils;
import com.p2p.auth.service.remote.IProductRemote;
import com.p2p.auth.service.repository.UserRepository;
import com.p2p.auth.domain.dto.user.UserAddDTO;
import com.p2p.auth.domain.dto.user.UserResponseDTO;
import com.p2p.auth.service.remote.ISms;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.hibernate.annotations.common.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Date;
import java.time.Instant;
import java.util.HashMap;
import java.util.UUID;

/**
 * Created by lipei on 2017/4/18.
 */

@RestController
@RequestMapping
@Api(value = "用户API", description = "用户的CRUD操作，注意必传参数与参数")
public class AppUserController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ISms smsRepository;

    @Autowired
    private IProductRemote productRemoteRepository;


    @Value("${user.zrll.retailersId}")
    public  String retailersId;

    @Value("${user.zrll.retailersName}")
    public  String retailersName;

    @Value("${user.zrll.retailersNo}")
    public  String retailersNo;



    @ApiOperation(value = "新用户注册", notes = "新用户注册 ", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParam(name = "userAddDTO", value = "根据用户名称与年龄，添加用户", required = true, dataType = "UserAddDTO")
    @ResponseBody
    @RequestMapping(value = Routes.APP_USER_ADD, method = RequestMethod.POST)
    public ResponseBase<UserResponseDTO> postUser(HttpServletRequest req, @RequestBody UserAddDTO userAddDTO) {
        ResponseBase<UserResponseDTO> result = new ResponseBase<>();

        if (null == userAddDTO || StringUtils.isEmpty(userAddDTO.getPhoneNum())) {
            result.setResultCode(ResultCode.PARAM_ERROR.getCode());
            result.setMsg("请先输入手机号");
            return result;
        }

        if (StringUtils.isEmpty(userAddDTO.getPhoneCode())) {
            result.setResultCode(ResultCode.PARAM_ERROR.getCode());
            result.setMsg("请输入验证码");
            return result;
        }

        logger.info("phoneNum ={}, phoneCode={}, retailersNo={}", userAddDTO.getPhoneNum(), userAddDTO.getPhoneCode(), userAddDTO.getRetailersNo());

        JsonResult jsonResult = smsRepository.validateCode(userAddDTO.getPhoneNum(), userAddDTO.getPhoneCode());

        logger.info("jsonResult = {}", jsonResult);

        if ( jsonResult == null || !jsonResult.getResultCode().equals(ResultCode.SUCC.getCode())) {
            result.setResultCode(ResultCode.PARAM_ERROR.getCode());
            result.setMsg("验证码不正确");
            return result;
        }

        User exists = userRepository.findByPhoneNum(userAddDTO.getPhoneNum());

        //如果用户已存在，直接返回用户信息
        if (null != exists) {
            UserResponseDTO respDto = UserUtils.copyToDTO(exists);
            result.setResult(respDto);
            result.setMsg("success");
            result.setResultCode(ResultCode.SUCC.getCode());
            return result;
        }

        User newUser = UserUtils.copyToPO(userAddDTO);

        String id = UUID.randomUUID().toString();

        newUser = addRetailerInfo(newUser, userAddDTO.getRetailersNo());

        newUser.setUserId(id);

        newUser.setDateCreated(Date.from(Instant.now()));

        if(StringHelper.isEmpty(newUser.getRetailersName())){
            newUser.setRetailersNo("000000");
            newUser.setRetailersName("自然流量");
        }

        userRepository.save(newUser);

        User respPo = userRepository.findByPhoneNum(userAddDTO.getPhoneNum());
        if (null == respPo) {
            result.setMsg("The given User must not be null!");
            result.setResultCode(ResultCode.NO_DATA.getCode());
            return result;
        }

        UserResponseDTO respDto = UserUtils.copyToDTO(respPo);
        result.setResult(respDto);
        result.setMsg("success");
        result.setResultCode(ResultCode.SUCC.getCode());
        return result;
    }





    @ApiOperation(value = "根据userId获取单一用户信息", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParam(paramType = "path", name = "userId", value = "用户ID", required = true, dataType = "String")
    @RequestMapping(value = Routes.APP_USER_INFO, method = RequestMethod.GET)
    public ResponseBase<UserResponseDTO> getUser(@PathVariable String userId) {
        ResponseBase<UserResponseDTO> result = new ResponseBase<>();
        if (StringUtils.isEmpty(userId)) {
            result.setMsg("The given userId must not be null!");
            result.setResultCode(ResultCode.PARAM_ERROR.getCode());
            return result;
        }

        User po = userRepository.findByUserId(userId);
        if (null == po) {
            result.setMsg("The given User must not be null!");
            result.setResultCode(ResultCode.NO_DATA.getCode());
            return result;
        }

        UserResponseDTO dto = UserUtils.copyToDTO(po);

        result.setResultCode(ResultCode.SUCC.getCode());
        result.setMsg("success");
        result.setResult(dto);

        return result;

    }

    @ApiOperation(value = "根据手机号获取单一用户信息", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParam(paramType = "path", name = "phoneNum", value = "用户ID", required = true, dataType = "String")
    @RequestMapping(value = Routes.APP_USER_INFO_BY_PHONENUM, method = RequestMethod.GET)
    public ResponseBase<UserResponseDTO> getInfoByPhoneNum(@PathVariable String phoneNum) {
        ResponseBase<UserResponseDTO> result = new ResponseBase<>();
        if (StringUtils.isEmpty(phoneNum)) {
            result.setMsg("The given phoneNum must not be null!");
            result.setResultCode(ResultCode.PARAM_ERROR.getCode());
            return result;
        }

        User po = userRepository.findByPhoneNum(phoneNum);
        if (null == po) {
            result.setMsg("The given User must not be null!");
            result.setResultCode(ResultCode.NO_DATA.getCode());
            return result;
        }

        UserResponseDTO dto = UserUtils.copyToDTO(po);
        result.setResultCode(ResultCode.SUCC.getCode());
        result.setMsg("success");
        result.setResult(dto);
        return result;

    }


    public User addRetailerInfo(User user, String inputRetailersNo){
        if(StringHelper.isEmpty(inputRetailersNo)){
            user.setRetailersId(retailersId);
            user.setRetailersNo(retailersNo);
            user.setRetailersName(retailersName);
            return  user;
        }

        HashMap userMsg =  productRemoteRepository.getRetailersMsgByRetailerNo(inputRetailersNo);

        logger.info("addRetailerInfo userMsg = {}", userMsg);
        if( userMsg != null && userMsg.get("retailerName")!= null){
            String retailerName = userMsg.get("retailerName").toString();
            user.setRetailersName(retailerName);
        }

        if( userMsg != null && userMsg.get("retailerNo")!= null){
            String retailerNo = userMsg.get("retailerNo").toString();
            user.setRetailersName(retailerNo);
        }

        if( userMsg != null && userMsg.get("retailerId")!= null){
            String retailerId = userMsg.get("retailerId").toString();
            user.setRetailersId(retailerId);
        }

        return  user;

    }
}
